package com.cmos.um.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cmos.um.beans.CtiMessageExtends;
import com.cmos.um.iservice.ICtiMessageSV;
import com.cmos.um.iservice.ICallRecordSV;
import com.cmos.um.utils.Result;
import com.cmos.um.utils.ResultUtil;
import com.cmos.um.utils.WSContent;
import com.cmos.um.utils.http.RestClientHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.MessageFormat;

@Service
public class CallRecordSVImpl implements ICallRecordSV {

    private final static Logger logger = LoggerFactory.getLogger(AgentSVImpl.class);
    @Autowired
    private ICtiMessageSV iCtiMessageSV;
    @Autowired
    private RestClientHttpRequest clien;

    /**
     * 话单查询接口
     * @param params
     * @return
     */
    @Override
    public Result findRecord(JSONObject params) {
        String serviceId  = params.getJSONObject("params").getString("serviceId");
        CtiMessageExtends ctiMessageExtends = iCtiMessageSV.queryCtimessageBytaskId(serviceId);
        if (ctiMessageExtends == null){
            logger.error("没有查询到此任务对应的cti");
            return ResultUtil.error("-9999","没有查询到此任务对应的cti");
        }
        String smpIp = ctiMessageExtends.getSmpIp();
        String taskXfId = ctiMessageExtends.getTaskXfId();
        String url = MessageFormat.format(WSContent.smpUrl, smpIp);
        logger.info("调用cti的话单查询接口："+url);
        JSONObject sendParams = new JSONObject();
        JSONArray callIds = params.getJSONObject("params").getJSONArray("callId");
        if (serviceId.equals("00000000")){
            taskXfId = "0000011111111100000000";
        }
        JSONArray beans = new JSONArray();
        for (Object callId : callIds) {
            sendParams.put("serviceid",taskXfId);
            sendParams.put("callid",callId);
            logger.info("发送的参数为："+sendParams);
            String ucCtx = clien.doPost(url, sendParams);
            logger.info("返回的信息为："+ucCtx);
            JSONObject result =JSONObject.parseObject(ucCtx);
            JSONObject bean = result.getJSONObject("output").getJSONArray("listsuc").getJSONObject(0);
            beans.add(bean);
        }

        return ResultUtil.success(beans);
    }
}
